var project = function () {

	var url = path + '/action/powerdb/designer/project/';

	//表格
	var projectTableSeletor = '#projectGridTable';

	var projectPagerSeletor = '#projectGridPager';

	var accountTableSeletor = '#accountGridTable';

	var accountPagerSeletor = '#accountGridPager';

	var addProjectRelAccountTableSeletor = '#addProjectRelAccountTable';

	var projectAccountTable = '#projectAccountTable';

	var projectAccountPager = '#projectAccountPager';

	var addProjRelAccJqgridTable = '#addProjRelAccJqgridTable';

	var addProjRelAccJqPagerTable = '#addProjRelAccJqPagerTable';

	//表单
	var projectSearchFormSelector = '#projectSearchForm';

	var projectAccountFormSeletor = '#projectAccountForm';

	var addProjRelAccModalForm = '#searchAccountForm';

	var addOrEditProjModalFormSeletor = '#projectAddOrEditModalForm';

	//弹窗
	var addOrEditProjModalSelector = '#projectAddOrEditModal';

	var addOrDelAccountModalSelector = '#accountAddOrDelModal';

	var projectAccountModalSeletor = '#projectAccountModal';


	var userInfoData;

	var projectId;

	var projectAccount;

	/** 枚举关键字定义 */
	var enums = ['pdm_account_rel_project-projectAuto', 'sec_account-sex'];

	/** 获取所有需要翻译的枚举 */
	var enumMap = sPost.getEnumMap(enums);

	var projectGridSetting = {
		gridId: projectTableSeletor,
		pagerId: projectPagerSeletor,
		datatype: 'local',
		data: [],
		gridHeightType: 2,
		//height: 130,
		url: null,
		mtype: "post",
		multiselect: false,
		rownumbers: true,
		autowidth: true,
		altRows: true,
		rowNum: 5,
		rowList: [5, 15, 30, 100],
		onSelectRow: function () {
			project.searchProjRelAcc();
		},

		colNames: ['id', '负责人id', '创建人id', '修改人id', '项目名称', '负责人', '创建人', '修改人', '创建时间', '修改时间', '项目描述'],
		colModel: [
			{name: 'id', index: 'id', width: 0, align: 'center', hidden: true},
			{name: 'projectAccountId', index: 'projectAccountId', width: 0, align: 'center', hidden: true},
			{name: 'createAccountId', index: 'createAccountId', width: 0, align: 'center', hidden: true},
			{name: 'modifyAccountId', index: 'modifyAccountId', width: 0, align: 'center', hidden: true},
			{name: 'name', index: 'name', width: 0, align: 'center'},
			{name: 'projectAccount', index: 'projectAccount', width: 0, align: 'center'},
			{name: 'createAccount', index: 'createAccount', width: 0, align: 'center'},
			{name: 'modifyAccount', index: 'modifyAccount', width: 0, align: 'center'},
			{name: 'createTime', index: 'createTime', width: 0, align: 'center'},
			{name: 'modifyTime', index: 'modifyTime', width: 0, align: 'center'},
			{name: 'remark', index: 'remark', width: 0, align: 'center'}
		]
	};

	var projRelAccGridSetting = {
		gridId: accountTableSeletor,
		pagerId: accountPagerSeletor,
		datatype: 'local',
		data: [],
		gridHeightType: 2,
		//height: 111,
		url: null,
		mtype: "post",
		multiselect: true,
		rownumbers: true,
		autowidth: true,
		altRows: true,
		rowNum: 5,
		rowList: [5, 15, 30, 100],
		colNames: ['id', '用户名称', '用户权限'],
		colModel: [
			{name: 'id', index: 'id', width: 0, align: 'center', hidden: true},
			{name: 'nameCn', index: 'nameCn', width: 0, align: 'center'},
			{name: 'projectAuto', index: 'projectAuto', width: 0, align: 'center'}
		]
	};

	var accGridSetting = {
		gridId: addProjRelAccJqgridTable,
		pagerId: addProjRelAccJqPagerTable,
		datatype: 'local',
		data: [],
		gridHeightType: 2,
		//height: 230,
		url: null,
		mtype: "post",
		multiselect: true,
		rownumbers: true,
		autowidth: true,
		rowNum: 10,
		rowList: [10, 30, 50],
		colNames: ['id', '中文名称', '性别', '手机', '电话'],
		colModel: [
			{name: 'id', index: 'id', width: 0, align: 'center', hidden: true},
			{name: 'nameCn', index: 'nameCn', width: 0, align: 'center'},
			{name: 'sex', index: 'sex', width: 0, align: 'center'},
			{name: 'cellPhone', index: 'cellPhone', width: 0, align: 'center'},
			{name: 'phone', index: 'phone', width: 0, align: 'center'}
		]
	};

	var projectAccountjqGridSetting = {
		gridId: projectAccountTable,
		pagerId: projectAccountPager,
		datatype: 'local',
		data: [],
		gridHeightType: 2,
		//height: 230,
		url: null,
		mtype: "post",
		multiselect: true,
		rownumbers: true,
		autowidth: true,
		rowNum: 10,
		rowList: [10, 30, 50],
		colNames: ['id', '中文名称', '性别', '手机', '电话'],
		colModel: [
			{name: 'id', index: 'id', width: 0, align: 'center', hidden: true},
			{name: 'nameCn', index: 'nameCn', width: 0, align: 'center'},
			{name: 'sex', index: 'sex', width: 0, align: 'center'},
			{name: 'cellPhone', index: 'cellPhone', width: 0, align: 'center'},
			{name: 'phone', index: 'phone', width: 0, align: 'center'}
		]
	};

	/**
	 * 获取当前登录用户的id
	 */
	function getCurAccountId() {
		//return accountId;
		return stroage.getSessionItem(CURRENT_USER_ID);
	}

	return {
		/**
		 初始化
		 1.下拉框加载枚举数据
		 2.初始化所有表格
		 3.查询所有项目信息，并填充到项目信息表格中
		 4.绑定按钮
		 */
		init: function () {

			function initEnum() {
				sUtils.select2Enum({
					selector: '#projectAuto',
					enums: enumMap.get('pdm_account_rel_project-projectAuto'),
					addAll: true
				});
			}

			function initGrid(setting) {
				grid.jqgird(setting);
				grid.notButton(setting['gridId'], setting['pagerId']);
				grid.destory(setting['gridId']);
				grid.reSize([setting]);

				//sGrid.jqgridSimple(setting);
				//sGrid.jqgridNotButton(setting['gridId'], setting['pagerId']);
				//sGrid.jqgridDestory(setting['gridId']);
				//sGrid.jqgridReSize(setting);
			}

			initEnum();
			project.searchProjectInfo(true);
			project.searchProjectInfo(false);

			initGrid(projRelAccGridSetting);
			initGrid(accGridSetting);

			sUtils.formValidClass(addOrEditProjModalFormSeletor);
		},

		/**
		 * 查找项目信息
		 * @param flag
		 * flag:true 首次加载，初始化表格 flag:false 二次加载，查找数据
		 */
		searchProjectInfo: function (flag) {

			if (flag) { //第一次加載

				grid.jqgird(projectGridSetting);
				grid.notButton(projectGridSetting['gridId'], projectGridSetting['pagerId']);
				grid.destory(projectGridSetting['gridId']);
				grid.reSize([projectGridSetting]);


				//sGrid.jqgridSimple(projectGridSetting);
				//sGrid.jqgridNotButton(projectGridSetting['gridId'], projectGridSetting['pagerId']);
				//sGrid.jqgridDestory(projectGridSetting['gridId']);
				//sGrid.jqgridReSize(projectGridSetting);
			} else { // 第二次加載
				/*
				 * 获取查询表单中的参数
				 * 请求action,获取返回数据
				 */
				var params = sUtils.getFormParams(projectSearchFormSelector);

				//查找
				var newUrl = url + "findProjectInfo";
				sPost.ajax(newUrl, params, function (data) {
					if (data.success) {
						//userInfoData = data.obj;
						//$(projectTableSeletor).clearGridData();
						//$(projectTableSeletor).setGridParam({data: userInfoData});
						//$(projectTableSeletor).trigger("reloadGrid");
						grid.reload(projectTableSeletor, data.obj);
					} else {
						layer.alert('查找项目失败！' + data.msg, {icon: 5, title: '提示'});
					}
				});
			}
		},

		/**
		 * 查找账户信息
		 * @param formId
		 *        表单Id
		 * @param tableId
		 *        表格Id
		 */
		searchAccountInfo: function (formId, tableId) {

			//FIXEME 有bug

			var params = sUtils.getFormParams(formId);
			var findAccountUrl = path + '/action/security/account/findPages';

			sPost.ajax(findAccountUrl, params, function (data) {
				if (data.success) {
					var resData = data.obj;
					sUtils.transactionEnum(resData.rows, enums, enumMap);
					$(tableId).clearGridData();
					if (resData != null) {
						$(tableId).setGridParam({data: resData.rows});
					}
					$(tableId).trigger("reloadGrid");
				} else {
					layer.alert('查找账户信息失败！' + data.msg, {icon: 5, title: '提示'});
				}
			});

		},

		/**
		 *  查找项目关联账户
		 */
		searchProjRelAcc: function () {
			//获取行id
			var rowId = $(projectTableSeletor).jqGrid('getGridParam', 'selrow');
			//获取行数据
			var resData = $(projectTableSeletor).jqGrid('getRowData', rowId);
			var tempUrl = url + "getAccounts";
			sPost.ajax(tempUrl, {'id': resData.id}, function (data) {
				if (data.success) {

					var accountData = data.obj;
					sUtils.transactionEnum(accountData, enums, enumMap);

					for (var i = 0; i < accountData.length; i++) {
						$.extend(true, accountData[i], {'name': resData.name});
					}
					//$(accountTableSeletor).clearGridData();
					//$(accountTableSeletor).setGridParam({data: accountData});
					//$(accountTableSeletor).trigger("reloadGrid");

					grid.reload(accountTableSeletor, accountData);
				} else {
					layer.alert('查找关联账户失败！' + data.msg, {icon: 5, title: '提示'});
				}
			});
		},

		/**
		 * 打开新增或修改项目信息弹窗
		 * @param flag
		 * true: 新增  false: 修改
		 */
		openWinAddOrEdit: function (flag) {

			function cleanOpenWin() {
				sUtils.cleanFrom(addOrEditProjModalFormSeletor);
				sUtils.validResetForm(addOrEditProjModalFormSeletor);
				$(addOrEditProjModalFormSeletor).find('#remark').val('');
				//如果有特殊控件，还需要特殊处理；
			}

			cleanOpenWin();

			if (!flag) { //修改
				var id = $(projectTableSeletor).jqGrid('getGridParam', 'selrow');
				// 判断是否选中
				if (sUtils.isNull(id)) {
					layer.alert('请选择要修改的项目！', {icon: 5, title: '提示'});
					return;
				}
				var data = $(projectTableSeletor).jqGrid('getRowData', id);
				sUtils.setFrom(addOrEditProjModalFormSeletor, data);
			}

			var title = flag ? '新增' : '修改';
			layer.open({
				type: 1,
				title: title,
				shadeClose: true,
				//shade: 0.8,
				area: ['600px', '300px'],
				content: $(addOrEditProjModalSelector),
				zIndex: 1000,
				btn: ['保存', '取消'],
				yes: function (at, layero) {

					if (flag == true && sUtils.isNull(projectAccount)) {
						layer.alert('请选择项目负责人！', {icon: 5, title: '提示'});
						return;
					}
					var result = project.saveOrEditProject(flag);
					if (result == true) {
						projectAccount = null;
						layer.close(at);
						project.searchProjectInfo(false);
					}
				}
			});
		},

		/**
		 打开新增关联账户弹窗
		 */
		openWinAddProjRelAcc: function () {

			projectId = $(projectTableSeletor).jqGrid('getGridParam', 'selrow');

			if (sUtils.isNull(projectId)) {
				layer.alert('请选择项目！', {icon: 5, title: '提示'});
				return;
			}

			function cleanOpenWin() {
				$(addProjectRelAccountTableSeletor)[0].options.length = 0;
				project.clearAccForm();
			}

			function initOpenWin() {
				sUtils.select2Enum({
					selector: '#projectRight',
					enums: enumMap.get('pdm_account_rel_project-projectAuto')
				});
				project.searchAccountInfo(addProjRelAccModalForm, addProjRelAccJqgridTable);
			}

			cleanOpenWin();
			initOpenWin();

			var at = layer.open({
				type: 1,
				title: '添加关联账户',
				shadeClose: true,
				//shade: 0.8,
				area: ['1100px', '520px'],
				content: $(addOrDelAccountModalSelector),
				zIndex: 1000
			});
			$('#closeOpenWinBtn').unbind('click').click(function () {
				layer.close(at);
			});
			$('#saveRelAccBtn').unbind('click').click(function () {
				if (-1 == project.saveProjectRelAccount()) {
					return;
				}
				layer.close(at);
				project.searchProjRelAcc();
			});
		},

		/**
		 * 打开选择项目负责人弹窗
		 */
		openWinSelectProjectAccount: function () {

			/*			sGrid.jqgridSimple(projectAccountjqGridSetting);
			 sGrid.jqgridReSize(projectAccountjqGridSetting);
			 sGrid.jqgridNotButton(projectAccountjqGridSetting['gridId'], projectAccountjqGridSetting['pagerId']);
			 sGrid.jqgridDestory(projectAccountjqGridSetting['gridId']);*/

			grid.jqgird(projectAccountjqGridSetting);
			grid.notButton(projectAccountjqGridSetting['gridId'], projectAccountjqGridSetting['pagerId']);
			grid.destory(projectAccountjqGridSetting['gridId']);
			grid.reSize([projectAccountjqGridSetting]);

			project.searchAccountInfo(projectAccountFormSeletor, projectAccountTable);
			var at = layer.open({
				type: 1,
				title: '选择项目负责人',
				shadeClose: true,
				//shade: 0.8,
				area: ['880px', '480px'],
				content: $(projectAccountModalSeletor),
				zIndex: 1000,
				btn: ['确定', '取消'],
				yes: function () {
					var id = $(projectAccountTable).jqGrid('getGridParam', 'selrow');
					// 判断是否选中
					if (sUtils.isNull(id)) {
						layer.alert('请选择项目负责人！', {icon: 5, title: '提示'});
						return;
					}
					projectAccount = $(projectAccountTable).jqGrid('getRowData', id);
					$('#projectAccount').val(projectAccount.nameCn);
					$('#accountId').val(projectAccount.id);
					layer.close(at);
				}
			});
		},

		/**
		 * 添加用户到已选表格
		 */
		addAccount: function () {
			var selectedIds = $(addProjRelAccJqgridTable).jqGrid("getGridParam", "selarrrow");
			var resData;
			var option;

			if (sUtils.isNull(selectedIds)) {
				layer.alert('请选择要添加的用户！', {icon: 5, title: '提示'});
				return;
			}

			var options = $('#addProjectRelAccountTable option');
			var addedAccountArr = options.map(function () {
				return $(this).val();
			});

			$.each(selectedIds, function (idx, val) {
				//判断下拉框有没有重复的id，如果有就不加进去
				if ($.inArray(val, addedAccountArr) == -1) {
					resData = $(addProjRelAccJqgridTable).jqGrid('getRowData', val);
					option = $("<option>").val(val).text(resData.nameCn);
					$(addProjectRelAccountTableSeletor).append(option);
				}
			});
		},

		/**
		 * 移除已添加的用户
		 */
		removeAddedAccount: function () {
			var $sel = $(addProjectRelAccountTableSeletor);
			var $option = $sel.find("option:selected");
			if ($option.length == 0) {
				layer.alert('请选择要移除的用户！', {icon: 5, title: '提示'});
			} else {
				$option.remove();
			}
		},

		/**
		 * 新增和修改项目
		 * @param flag
		 *    true: 新增 false: 修改
		 */
		saveOrEditProject: function (flag) {
			/*
			 获取表单数据
			 */
			var params = sUtils.getFormParams(addOrEditProjModalFormSeletor);
			var result = false;
			if ($(addOrEditProjModalFormSeletor).valid()) {
				result = true;
				if (flag) {

					params.createAccountId = getCurAccountId();
					params.modifyAccountId = getCurAccountId();

					sPost.ajax(url, params, function (data) {
						if (data.success) {
							params = data;
							layer.alert('新增成功！', {icon: 1, title: '提示'});
						} else {
							layer.alert('新增失败！' + data.msg, {icon: 5, title: '提示'});
							result = false;
						}
					});
				} else {
					params.modifyAccountId = getCurAccountId();
					params.accountId = params['projectAccountId'];
					sPost.ajaxPut(url, params, function (data) {
						if (data.success) {
							params = data;
							layer.alert('修改成功！', {icon: 1, title: '提示'});
						} else {
							layer.alert('修改失败！' + data.msg, {icon: 5, title: '提示'});
							result = false;
						}
					});
				}
			}
			return result;
		},

		/**
		 *  添加项目关联账户关系
		 */
		saveProjectRelAccount: function () {

			var options = $('#addProjectRelAccountTable option');
			var selParams = $('#projectRight').val();
			if (options.length == 0) {
				layer.alert('请选择要保存的用户！', {icon: 5, title: '提示'});
				return -1;
			}
			var accountIds = options.map(function () {
				return $(this).val();
			}).get().join(",");

			sPost.ajax(url + 'savaRel', {
				'id': parseFloat(projectId),
				'ids': accountIds,
				'right': selParams
			}, function (data) {
				if (data.success) {
					layer.alert('添加项目关联账户关系成功！', {icon: 1, title: '提示'});
				} else {
					layer.alert('添加项目关联账户关系失败！' + data.msg, {icon: 5, title: '提示'});
					return -1;
				}
			});
		},

		/**
		 * 删除项目
		 */
		delProject: function () {
			var id = $(projectTableSeletor).jqGrid('getGridParam', 'selrow');
			// 根据id获取选中行数据
			var resData = $(projectTableSeletor).jqGrid('getRowData', id);
			// 判断是否选中
			if (sUtils.isNull(id)) {
				layer.alert('请选择要删除的项目！', {icon: 5, title: '提示'});
				return;
			}
			if ($(accountTableSeletor).getGridParam("reccount") != 0) {
				layer.alert('请先删除该项目关联的用户！', {icon: 5, title: '提示'});
				return;
			}
			layer.confirm('确定要删除' + resData.name + '吗？', {icon: 3, title: '提示'}, function (index) {
				var delUrl = url + resData.id;
				sPost.ajaxDel(delUrl, {}, function (data) {
					if (data.success) {
						layer.alert('删除成功！', {icon: 1, title: '提示'});
						$(projectTableSeletor).jqGrid('delRowData', id);
						layer.close(index);
					} else {
						layer.alert('删除失败！' + data.msg, {icon: 5, title: '提示'});
					}
				});
			});
		},

		/**
		 *  删除数据库关联账户表格条目
		 */
		delProjectRelAccount: function () {
			/*
			 判断是否选中
			 二次确认
			 */
			var selectedIds = $(accountTableSeletor).jqGrid("getGridParam", "selarrrow");

			var id = $(projectTableSeletor).jqGrid('getGridParam', 'selrow');

			// 判断是否选中
			if (sUtils.isNull(selectedIds)) {
				layer.alert('请选择要删除的用户！', {icon: 5, title: '提示'});
				return;
			}

			var accountIds = selectedIds.join(",");

			layer.confirm('确定要删除吗？', {icon: 3, title: '提示'}, function (index) {

				var delUrl = path + "/action/powerdb/designer/project/delRel";

				sPost.ajax(delUrl, {'id': parseFloat(id), 'ids': accountIds}, function (data) {
					if (data.success) {
						/*
						 selectedId会动态减少，故每次只删除数组的第一个元素，直到数组个数为0
						 不能用循环
						 */
						while (selectedIds.length) {
							$(accountTableSeletor).jqGrid("delRowData", selectedIds[0]);
						}
						layer.alert('删除成功！', {icon: 1, title: '提示'});
					} else {
						layer.alert('删除失败！' + data.msg, {icon: 5, title: '提示'});
					}
				});
				layer.close(index);
			});
		},

		/**
		 * 清空项目搜索查询条件
		 */
		clearProjForm: function () {
			sUtils.cleanFrom(projectSearchFormSelector);
			project.searchProjectInfo(false);

		},

		/**
		 * 清空用户搜索查询条件
		 */
		clearAccForm: function () {
			sUtils.cleanFrom(addProjRelAccModalForm);
			$('#userDelStatus').val(0);
			project.searchAccountInfo(addProjRelAccModalForm, addProjRelAccJqgridTable);
		},

		/**
		 * 清空项目负责人索查询条件
		 */
		clearProjAccForm: function () {
			sUtils.cleanFrom(projectAccountFormSeletor);
			$('#accountDelStatus').val(0);
			project.searchAccountInfo(projectAccountFormSeletor, projectAccountTable);
		}
	}
}();
